<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类</span>
          <!-- 级联选择框 -->
          <div class="block">
            <el-cascader
              v-model="selectCateKeys"
              :options="paramsList"
              :props="paramsProps"
              @change="handleChange"
            ></el-cascader>
          </div>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="buttonIsDisabled"
            @click="addAttrDialog"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <template>
            <el-table :data="manyAttrList" style="width: 100%">
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    effect="dark"
                    closable
                    type="warning"
                    @close="handleClosed(i, scope.row)"
                    >{{ item }}</el-tag
                  >
                  <!-- tag标签 -->
                  <!-- 输入的文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.tagInputVisable"
                    v-model="scope.row.tagInputValue"
                    ref="tagInputRef"
                    size="small"
                    @keyup.enter.native="tagInputConfirm(scope.row)"
                    @blur="tagInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加的按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"> </el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="editDialogOpen(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="removeParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="buttonIsDisabled"
            @click="addAttrDialog"
            >添加属性</el-button
          >
          <template>
            <el-table :data="onlyAttrList" style="width: 100%">
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    effect="dark"
                    closable
                    type="warning"
                    @close="handleClosed(i, scope.row)"
                    >{{ item }}</el-tag
                  >
                  <!-- tag标签 -->
                  <!-- 输入的文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.tagInputVisable"
                    v-model="scope.row.tagInputValue"
                    ref="tagInputRef"
                    size="small"
                    @keyup.enter.native="tagInputConfirm(scope.row)"
                    @blur="tagInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加的按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"> </el-table-column>
              <el-table-column prop="attr_name" label="属性名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="editDialogOpen(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="removeParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加数据对话框 -->
    <el-dialog
      :title="'添加' + dialogTitle"
      :visible.sync="attrDialog"
      width="50%"
      @close="addAttrClosed"
    >
      <el-form
        :model="addAttrModel"
        :rules="addAttrModelRules"
        ref="addAttrModelRef"
        label-width="100px"
      >
        <el-form-item :label="dialogTitle" prop="attr_name">
          <el-input v-model="addAttrModel.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="attrDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + dialogTitle"
      :visible.sync="editDialog"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editDialogModel"
        :rules="editDialogRules"
        ref="editDialogref"
        label-width="100px"
      >
        <el-form-item :label="dialogTitle" prop="attr_name">
          <el-input v-model="editDialogModel.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 所有商品分类列表
      paramsList: [],
      // 级联选择框的配置选项
      paramsProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向绑定的数组
      selectCateKeys: [],
      // 绑定值，选中选项卡的 name
      activeName: 'many',
      // 获取的动态参数列表
      manyAttrList: [],
      // 获取的静态属性列表
      onlyAttrList: [],
      // 对话框开闭状态
      attrDialog: false,
      // 添加属性input绑定的数据
      addAttrModel: {
        attr_name: ''
      },
      // 添加表单的验证规则的对象
      addAttrModelRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改按钮开闭状态
      editDialog: false,
      // 修改按钮绑定数据
      editDialogModel: [],
      // 修改按钮验证规则
      editDialogRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getpapamsList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return
      this.paramsList = res.data
    },
    // 级联选择框数据变化绑定的函数
    async handleChange (value) {
      // 选中的不是三级分类
      // value为配置的value组成的数组 相当于selectCateKeys
      if (value.length !== 3) {
        this.manyAttrList = []
        this.onlyAttrList = []
        // value不能反向设置级联选择器里的值,只能用与它双向绑定的selectCateKeys
        this.selectCateKeys = []
        return this.$message.error('只允许选择第三级数据！')
      }
      // 选择框数据变化时获取参数列表
      this.getAttrList()
      this.tabButtonDisabled = false
    },
    // tab页签点击函数
    tabHandleClick () {
      if (this.selectCateKeys.length !== 3) {
        return this.$message.error('请先选择商品分类！')
      }
      this.getAttrList()
    },
    // 获取参数列表
    async getAttrList () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // tag标签显示/隐藏
        item.tagInputVisable = false
        // tag标签输入的数据
        item.tagInputValue = ''
      })
      // 判断获取的数据属于哪个表格
      if (this.activeName === 'many') {
        this.manyAttrList = res.data
      } else {
        this.onlyAttrList = res.data
      }
    },
    // 打开添加属性对话框
    addAttrDialog () {
      this.attrDialog = true
    },
    // 监听添加对话框的关闭事件
    addAttrClosed () {
      this.$refs.addAttrModelRef.resetFields()
    },
    // 提交添加属性事件函数
    addParams () {
      this.$refs.addAttrModelRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入属性名称')
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateID}/attributes`,
          {
            attr_name: this.addAttrModel.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.attrDialog = false
        this.getAttrList()
      })
    },
    // 监听编辑表单关闭事件
    editDialogClosed () {
      this.$refs.editDialogref.resetFields()
    },
    // 修改按钮单击函数
    async editDialogOpen (id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editDialogModel = res.data

      this.editDialog = true
    },
    // 修改对话框提交数据
    editParams () {
      this.$refs.editDialogref.validate(async valid => {
        if (!valid) {
          return this.$message.error('校验失败')
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateID}/attributes/${this.editDialogModel.attr_id}`,
          {
            attr_name: this.editDialogModel.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.getAttrList()
        this.editDialog = false
      })
    },
    // 单机删除按钮触发移除参数事件
    async removeParams (id) {
      const confirm = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (confirm === 'confirm') {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateID}/attributes/${id}`
        )
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功！')
        this.getAttrList()
      }
    },
    // tag标签blur
    async tagInputConfirm (row) {
      if (row.tagInputValue.trim().length === 0) {
        row.tagInputValue = ''
        row.tagInputVisable = false
        return this.$message.error('输入有误，请重新输入')
      }
      // 没有return的后续处理
      row.attr_vals.push(row.tagInputValue.trim())
      // 发起请求保存操作
      const { data: res } = await this.$http.put(
        `categories/${this.cateID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('修改参数项成功！')
      row.tagInputValue = ''
      row.tagInputVisable = false
    },
    // 单击tag显示input
    showInput (row) {
      row.tagInputVisable = true
      // 自动焦点
      // this.$nextTick:当页面上的元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.tagInputRef.$refs.input.focus()
      })
    },
    // 删除参数可选项
    async handleClosed (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(
        `categories/${this.cateID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('修改参数项成功！')
    }
  },
  computed: {
    // 如果按钮被禁用返回true 否则返回false
    buttonIsDisabled () {
      if (this.selectCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 用于获取第三级id的计算属性
    cateID () {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[this.selectCateKeys.length - 1]
      }
      return null
    },
    // 对话框显示字节
    dialogTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created () {
    this.getpapamsList()
  }
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}

.el-alert {
  margin-bottom: 20px;
}
.block {
  display: inline-block;
  margin-left: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 89px;
}
</style>
